package com.ruoyi.web.service.Impl;

import java.math.BigDecimal;
import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.pinyin.PinYinUtils;
import com.ruoyi.web.domain.*;
import com.ruoyi.web.domain.mes.MesMachinePaper;
import com.ruoyi.web.domain.mes.MesPaper;
import com.ruoyi.web.domain.vo.MesUseDetailVo;
import com.ruoyi.web.mapper.MesConfigMapper;
import com.ruoyi.web.service.MesCuttingGroupService;
import com.ruoyi.web.service.MesMachineService;
import com.ruoyi.web.vo.MesMachine;
//import com.ruoyi.web.vo.ProducePiece;
import org.springframework.stereotype.Service;

import java.util.stream.Collectors;

import com.ruoyi.common.utils.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.web.mapper.MesUseInfoMapper;
import com.ruoyi.web.service.IMesUseInfoService;

import javax.annotation.Resource;

/**
 * 纸张领用单Service业务层处理
 *
 * @author wxt
 * @date 2024-01-17
 */
@Service
public class MesUseInfoServiceImpl implements IMesUseInfoService {
    @Resource
    private MesUseInfoMapper mesUseInfoMapper;
    @Resource
    private MesPaperService mesPaperService;
    @Resource
    private MesConfigMapper configMapper;
    @Resource
    private MesMachineService mesMachineService;

    @Resource
    private MesCuttingGroupService mesCuttingGroupService;

    /**
     * 查询纸张领用单
     *
     * @param id 纸张领用单主键
     * @return 纸张领用单
     */
    @Override
    public MesUseInfo selectMesUseInfoById(Long id) {
        return mesUseInfoMapper.selectMesUseInfoById(id);
    }

    /**
     * 查询纸张领用单列表
     *
     * @param mesUseInfo 纸张领用单
     * @return 纸张领用单
     */
    @Override
    public List<MesUseInfo> selectMesUseInfoList(MesUseInfo mesUseInfo) {
        return mesUseInfoMapper.selectMesUseInfoList(mesUseInfo);
    }

    @Override
    public List<MesUseDetailVo> selectUseDetail(MesUseDetailVo useDetail) {
        List<MesUseDetailVo> mesUseDetailVos = mesUseInfoMapper.selectUseDetail(useDetail);
        return mesUseDetailVos;
    }

    @Override
    public List<MesUseDetailVo> selectMesDetaillist(MesUseInfo mesUseInfo) {
        List<MesUseDetailVo> mesUseDetailVos = mesUseInfoMapper.selectMesDetaillist(mesUseInfo);
//        BigDecimal decimal = mesUseInfoMapper.selectMesDetaillistaSumUseNumber(mesUseInfo);
//        if(mesUseDetailVos.size() > 0){
//            mesUseDetailVos.get(0).setUseNumberSum(decimal);
//        }
        return mesUseDetailVos;
    }

    /**
     * 新增纸张领用单
     *
     * @param mesUseInfo 纸张领用单
     * @return 结果
     */
    @Transactional
    @Override
    public int insertMesUseInfo(MesUseInfo mesUseInfo) {
        mesUseInfo.setCreateTime(DateUtils.getNowDate());

        // 生成领用单编号
//        int maxNum = mesUseInfoMapper.getmes_use_infoMaxId();

        Map<String, Object> map = new HashMap<>();
        map.put("columnName", "use_num");
        map.put("tableName", "mes_use_info");
        int maxNum = configMapper.getMaxId(map);

        String code = PinYinUtils.getCodeNormal(maxNum, "ZZLYD");
        mesUseInfo.setUseNum(code);

        int rows = mesUseInfoMapper.insertMesUseInfo(mesUseInfo);
        insertMesUseDetail(mesUseInfo);
        return rows;
    }

    /**
     * 修改纸张领用单
     *
     * @param mesUseInfo 纸张领用单
     * @return 结果
     */
    @Transactional
    @Override
    public int updateMesUseInfo(MesUseInfo mesUseInfo) {
        int status = mesUseInfo.getStatus();
//        boolean machineType=false;//是否类型是印刷机并且机型是平张
        if (status == 2) {  //提交
            MesUseInfo Info = mesUseInfoMapper.selectMesUseInfoById(mesUseInfo.getId());//领用主表
            List<MesUseDetail> MesUseDetailList = Info.getMesUseDetailList();//领用详情


            //MesMachine mesMachine = mesMachineService.getById(mesUseInfo.getUseMachineid());//机台
            MesMachine mesMachine = mesMachineService.getById(Info.getUseMachineid());//机台
//            //判断是印刷机平张
//            if(Objects.equals(mesMachine.getType(), "2")&& Objects.equals(mesMachine.getModel(), "1")){
//                machineType=true;
//            }


            if (MesUseDetailList.size() != 0) {
                // 获取纸张ids
                List<Long> listId = MesUseDetailList.stream().map(it -> it.getPaperid()).collect(Collectors.toList());
                Long[] ids = listId.toArray(new Long[0]);

                //根据机台id和纸张id查询裁切机台可用库存量
                if (Objects.equals(Info.getType(), "1")) {//判断平张
                    MesMachinePaper machinePaper = new MesMachinePaper();
                    machinePaper.setPaperids(ids);//纸张id
                    machinePaper.setMachineid(Info.getOutMachineid());//机台id
                    List<MesMachinePaper> MPaper = mesPaperService.selectMachinePaperByIds(machinePaper);

                    for (MesUseDetail mesUseDetail : MesUseDetailList) {
//                        List<MesMachinePaper> mesMachinePaper = MPaper.stream().filter(it -> it.getPaperid().equals(mesUseDetail.getPaperid())
//                        ).collect(Collectors.toList());
//                        if (mesMachinePaper != null && mesMachinePaper.size() != 0) {
//                            BigDecimal total = mesUseDetail.getUseNumber();
//                            int result = mesMachinePaper.get(0).getResidueNumber().compareTo(total);
//                            if (result < 0) {
//                                throw new ServiceException("领用数量大于机台裁切数量！");
//                            }
//                        } else {
//                            throw new ServiceException("领用数量大于机台裁切数量！");
//                        }
                        List<MesCuttingGroup> mesCuttingGroups = mesCuttingGroupService.list(new QueryWrapper<MesCuttingGroup>().lambda()
                                .eq(MesCuttingGroup::getPaperId, mesUseDetail.getPaperid()));
                        if (mesCuttingGroups != null && mesCuttingGroups.size() > 0) {
                            double cutting = mesCuttingGroups.get(0).getCuttingNum();
                            BigDecimal total = mesUseDetail.getUseNumber();
                            int result = mesCuttingGroups.get(0).getCuttingNum().compareTo(total.doubleValue());
                            if (result < 0) {
                                throw new ServiceException("领用数量大于机台裁切组数量！");
                            }
                        }
                    }
//                    for (MesMachinePaper mesMachinePaper : MPaper) {
//                        if (Objects.equals(mesUseDetail.getPaperid(), mesMachinePaper.getPaperid())){
//                            Double total = mesUseDetail.getUseNumber().doubleValue();
//                            int result = mesMachinePaper.getResidueNumber().compareTo(total);
//                            if (result < 0) {
//                                throw new ServiceException("领用数量大于机台裁切数量！");
//                            }
//                        }
//                    }

                } else {
                    // 根据纸张ids查询纸张库存明细
                    List<MesPaper> detailList = mesPaperService.selectMesPaperByIds(ids);
                    for (MesUseDetail UseDetail : MesUseDetailList) {
                        for (MesPaper paper : detailList) {
                            if (paper.getId().equals(UseDetail.getPaperid())) {
                                BigDecimal total = UseDetail.getUseNumber();
                                if (paper.getQuantity() == null) {
                                    throw new ServiceException(paper.getName() + "纸张没有库存为空！");
                                }
                                int result = paper.getQuantity().compareTo(total);
                                if (result < 0) {
                                    throw new ServiceException("领用数量大于纸张库存数量！");
                                }
                            }
                        }
                    }
                }
            }
            for (MesUseDetail mesuseDetail : MesUseDetailList) {
                if (Info.getUseMachineid() != null && Info.getUseMachineid() != "" && mesuseDetail.getPaperid() != null) {
                    updateQuantity(Info.getUseMachineid(), mesuseDetail.getPaperid(), Info.getOutMachineid(), mesuseDetail.getUseNumber(), mesuseDetail.getProducePaperid(), Info.getType());
                    //   updateCutting(mesuseDetail.getPaperid(),mesuseDetail.getUseNumber());
                }
            }
        } else {
            mesUseInfoMapper.deleteMesUseDetailByUseinfoid(mesUseInfo.getId());//删除子表
            insertMesUseDetail(mesUseInfo);
        }
        return mesUseInfoMapper.updateMesUseInfo(mesUseInfo);
    }

    /**
     * 批量删除纸张领用单
     *
     * @param ids 需要删除的纸张领用单主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteMesUseInfoByIds(Long[] ids) {
        mesUseInfoMapper.deleteMesUseDetailByUseinfoids(ids);
//        for (long id : ids) {
//            MesUseInfo Info = mesUseInfoMapper.selectMesUseInfoById(id);
//            mesUseInfoMapper.deleteMesUseDetailByUseinfoid(id);
//            List<MesUseDetail> MesUseDetailList = Info.getMesUseDetailList(); //删除加库存
//            for (MesUseDetail mesuseDetail : MesUseDetailList) {
//                updateQuantity(mesuseDetail.getPaperid(),mesuseDetail.getUseNumber(),1);
//            }
//        }
        return mesUseInfoMapper.deleteMesUseInfoByIds(ids);
    }

    /**
     * 删除纸张领用单信息
     *
     * @param id 纸张领用单主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteMesUseInfoById(Long id) {
        //MesUseInfo Info= mesUseInfoMapper.selectMesUseInfoById(id);
        mesUseInfoMapper.deleteMesUseDetailByUseinfoid(id);
//        List<MesUseDetail> MesUseDetailList = Info.getMesUseDetailList();//删除加库存
//
//        for (MesUseDetail mesuseDetail : MesUseDetailList)
//        {
//            updateQuantity(mesuseDetail.getPaperid(),mesuseDetail.getUseNumber(),1);
//        }
        return mesUseInfoMapper.deleteMesUseInfoById(id);
    }

    /**
     * 新增纸张领用明细信息
     *
     * @param mesUseInfo 纸张领用单对象
     */
    public void insertMesUseDetail(MesUseInfo mesUseInfo) {
        List<MesUseDetail> mesUseDetailList = mesUseInfo.getMesUseDetailList();
        Long id = mesUseInfo.getId();
        if (StringUtils.isNotNull(mesUseDetailList)) {
            List<MesUseDetail> list = new ArrayList<MesUseDetail>();
            for (MesUseDetail mesUseDetail : mesUseDetailList) {
                mesUseDetail.setUseinfoid(id);
                list.add(mesUseDetail);
            }
            if (list.size() > 0) {
                mesUseInfoMapper.batchMesUseDetail(list);
            }
        }
    }

//    private void updateCutting(Long paperid, BigDecimal number){
//        //减裁切组裁切库存
//        mesCuttingGroupService.update( new UpdateWrapper<MesCuttingGroup>().lambda()
//                .setSql("cutting_num = cutting_num - " + number)
//                .eq(MesCuttingGroup::getPaperId,paperid));
//    }


    private void updateQuantity(String machineid, Long paperid, String OutMachineid, BigDecimal number, String producePaperId, String machineType) {

        MesMachinePaper machinepaper = new MesMachinePaper();

        machinepaper.setPaperid(paperid);
        machinepaper.setNumber(number);

        if (Objects.equals(machineType, "1")) {//如果是平张
//            machinepaper.setMachineid(OutMachineid);
//            machinepaper.setType((long) 2);
//            mesPaperService.cuttingMachinePaper(machinepaper);//减裁切机台库存
//减裁切库存
            mesCuttingGroupService.update(new UpdateWrapper<MesCuttingGroup>().lambda()
                    .setSql("cutting_num = cutting_num - " + number)
                    .eq(MesCuttingGroup::getPaperId, paperid));

        } else {
            MesPaper paper = new MesPaper();
            paper.setId(paperid);
            paper.setQuantity(number);
            paper.setQuantitymark(2);
            mesPaperService.updateMesPaperQuantity(paper);//减纸库库存
        }

        machinepaper.setType((long) 1);
        machinepaper.setMachineid(machineid);
        int id = mesPaperService.selectMachinePaper(machinepaper);//查询机台纸张
        if (id > 0) {
            mesPaperService.updateMachinePaper(machinepaper);//增加机台库存
        } else {
            mesPaperService.AddMachinePaper(machinepaper);//添加机台纸张
        }

        MesUseDetail use = new MesUseDetail();
        use.setType(1);
        use.setProducePaperid(producePaperId);
        use.setUseNumber(number);
        mesPaperService.updateProducePaperUseAmount(use);//更改生产单已领用数量
    }


}
